package com.bieyang.anjia.ui.activity;

import java.util.Calendar;
import java.util.Iterator;
import java.util.TreeSet;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.bieyang.anjia.R;
import com.bieyang.anjia.module.Device;
import com.bieyang.anjia.net.NetManager;
import com.bieyang.anjia.ui.widget.RepeatDayChooseDialog;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SharedPrefsUtil;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.SubUtils;

/**
 * 预警时段
 * @author Administrator
 *
 */
public class AlarmTimeActivity extends BaseNomalActivity implements
		OnClickListener, RepeatDayChooseDialog.DialogRefresh {
	private TextView dayStartTv, nightStartTv, dayStopTv, nightStopTv,
			repeatDay;
	private RelativeLayout dayStartRelativeLayout, dayStopRelativeLayout,
			nightStartRelativeLayout, nightStopRelativeLayout,
			repeatRelativeLayout;
	private Activity activity;
	private AlertDialog dialog;
	private String[] items;
	private RepeatDayChooseDialog repeatDialog;
	private TreeSet<Integer> chooseDay, lastRepeatDay;
	private SubUtils subUtils = new SubUtils();
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Constants.SET_SUB_SET_SUCCESS:
				progressDialog.dismiss();
				Log.d("saveSetting", "success");
				SharedPrefsUtil.putValue(activity,
						Constants.DAY_MODE_START_TIME, dayStartTv.getText()
								.toString());
				SharedPrefsUtil.putValue(activity,
						Constants.DAY_MODE_STOP_TIME, dayStopTv.getText()
								.toString());
				SharedPrefsUtil.putValue(activity,
						Constants.NIGHT_MODE_START_TIME, nightStartTv.getText()
								.toString());
				SharedPrefsUtil.putValue(activity,
						Constants.NIGHT_MODE_STOP_TIME, nightStopTv.getText()
								.toString());
				setResult(2001);
				Show.toast(con, R.string.save_device_ok);
				finish();
				break;
			case Constants.SET_SUB_SET_FAILED:
				saveWeekDays(lastRepeatDay);
				progressDialog.dismiss();
				Show.toast(con, R.string.save_device_fail);
				finish();
				break;

			default:
				break;
			}
		};
	};

	@Override
	void setContent() {
		activity = this;
		setContentView(R.layout.alarm_time_layout);
		items = new String[] { getString(R.string.sub_time_everyday),
				getString(R.string.sub_time_workday),
				getString(R.string.sub_time_custom) };
	}

	@Override
	void initView() {
		TextView titleName = (TextView) findViewById(R.id.topLineTitle);
		titleName.setText(getString(R.string.sub_alarm_time));
		dayStartTv = (TextView) findViewById(R.id.dayStarttv);
		dayStopTv = (TextView) findViewById(R.id.dayStoptv);
		nightStartTv = (TextView) findViewById(R.id.nightStarttv);
		nightStopTv = (TextView) findViewById(R.id.nightStoptv);
		repeatDay = (TextView) findViewById(R.id.repeat_day);
		dayStartRelativeLayout = (RelativeLayout) findViewById(R.id.dayStartRelativelayout);
		dayStopRelativeLayout = (RelativeLayout) findViewById(R.id.dayStopRelativelayout);
		nightStartRelativeLayout = (RelativeLayout) findViewById(R.id.nightStartRelativelayout);
		nightStopRelativeLayout = (RelativeLayout) findViewById(R.id.nightStopRelativelayout);
		repeatRelativeLayout = (RelativeLayout) findViewById(R.id.repeatRelativeLayout);
		dialog = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)
				.setTitle(activity.getString(R.string.sub_time_repeat))
				.setItems(items, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which) {
						case 0:
							repeatDay.setText(items[which]);
							TreeSet<Integer> everyDay = new TreeSet<Integer>();
							for (int i = 0; i < 7; i++) {
								everyDay.add(i + 1);
							}
							saveWeekDays(everyDay);
							reFresh(everyDay);
							dialog.dismiss();
							break;
						case 1:
							repeatDay.setText(items[which]);
							TreeSet<Integer> workDay = new TreeSet<Integer>();
							for (int i = 0; i < 5; i++) {
								workDay.add(i + 2);
							}
							saveWeekDays(workDay);
							reFresh(workDay);
							dialog.dismiss();
							break;
						case 2:
							repeatDialog.showDialog();
							dialog.dismiss();
							break;
						default:
							dialog.dismiss();
							break;
						}
					}
				}).create();
		repeatDialog = new RepeatDayChooseDialog(activity,
				AlarmTimeActivity.this);
	}

	/**
	 * 保存每周重复天数设置
	 * 
	 * @param chooseDay
	 */
	private void saveWeekDays(TreeSet<Integer> chooseDay) {
		SharedPrefsUtil.putSetValue(activity, Constants.WEEK_DAY,
				new SubUtils().getWeekSet(activity, chooseDay));
	}

	@Override
	void initData() {
		dayStartTv.setText(SharedPrefsUtil.getStringValue(activity,
				Constants.DAY_MODE_START_TIME,
				getString(R.string.sub_mode_start_time)));
		dayStopTv.setText(SharedPrefsUtil.getStringValue(activity,
				Constants.DAY_MODE_STOP_TIME,
				getString(R.string.sub_mode_stop_time)));
		nightStartTv.setText(SharedPrefsUtil.getStringValue(activity,
				Constants.NIGHT_MODE_START_TIME,
				getString(R.string.sub_night_start_time)));
		nightStopTv.setText(SharedPrefsUtil.getStringValue(activity,
				Constants.NIGHT_MODE_STOP_TIME,
				getString(R.string.sub_night_stop_time)));
		chooseDay = subUtils.getWeekDaySet(AlarmTimeActivity.this,
				SharedPrefsUtil.getSetValue(AlarmTimeActivity.this,
						Constants.WEEK_DAY,
						subUtils.initWeekSet(AlarmTimeActivity.this)));
		lastRepeatDay = subUtils.getWeekDaySet(AlarmTimeActivity.this,
				SharedPrefsUtil.getSetValue(AlarmTimeActivity.this,
						Constants.WEEK_DAY,
						subUtils.initWeekSet(AlarmTimeActivity.this)));
		reFresh(chooseDay);

	}

	@Override
	void setListener() {
		dayStartRelativeLayout.setOnClickListener(this);
		dayStopRelativeLayout.setOnClickListener(this);
		nightStartRelativeLayout.setOnClickListener(this);
		nightStopRelativeLayout.setOnClickListener(this);
		repeatRelativeLayout.setOnClickListener(this);
	}

	/**
	 * 时间选择框显示
	 * 
	 * @param timeTv
	 */
	private void showTimePickerDialog(final TextView timeTv) {
		int hour = 0, minute = 0;
		String time = timeTv.getText().toString();
		if (null != time && !time.trim().isEmpty()) {
			try {
				hour = Integer.parseInt(time.substring(0, 2));
				minute = Integer.parseInt(time.substring(time.length() - 2));
			} catch (Exception e) {
				switch (timeTv.getId()) {
				case R.id.dayStarttv:
					hour = Constants.DAY_START_HOUR;
					minute = 0;
					break;
				case R.id.dayStoptv:
					hour = Constants.DAY_STOP_HOUR;
					minute = 0;
					break;
				case R.id.nightStarttv:
					hour = Constants.NIGHT_START_HOUR;
					minute = 0;
					break;
				case R.id.nightStopRelativelayout:
					hour = Constants.NIGHT_STOP_HOUR;
					minute = 0;
					break;
				default:
					break;
				}
			}

		}

		new TimePickerDialog(activity, TimePickerDialog.THEME_HOLO_LIGHT,
				new TimePickerDialog.OnTimeSetListener() {

					@Override
					public void onTimeSet(TimePicker view, int hourOfDay,
							int minute) {
						boolean canSet = false;
						switch (timeTv.getId()) {
						case R.id.dayStarttv:
							canSet = compareTime(hourOfDay, minute, dayStopTv,
									true);
							break;
						case R.id.dayStoptv:
							canSet = compareTime(hourOfDay, minute, dayStartTv,
									true);
							break;
						case R.id.nightStarttv:
							canSet = compareTime(hourOfDay, minute,
									nightStopTv, false);
							break;
						case R.id.nightStoptv:
							canSet = compareTime(hourOfDay, minute,
									nightStartTv, false);
							break;
						default:
							break;
						}
						if (canSet) {
							setTimeText(timeTv, hourOfDay, minute);
						}
					}
				}, hour, minute, true).show();

	}

	/**
	 * 设置时间
	 * 
	 * @param timeTv
	 *            显示控件
	 * @param hour
	 *            小时
	 * @param minute
	 *            分钟
	 */
	private void setTimeText(TextView timeTv, int hour, int minute) {
		StringBuffer sb = new StringBuffer("");
		if (hour < 10) {
			sb.append(0);
		}
		sb.append(hour);
		sb.append(":");
		if (minute < 10) {
			sb.append(0);
		}
		sb.append(minute);
		timeTv.setText(sb.toString());
	}

	@Override
	public void onClick(View v) {
		isSetted = true;
		switch (v.getId()) {
		case R.id.dayStartRelativelayout:
			showTimePickerDialog(dayStartTv);
			break;
		case R.id.dayStopRelativelayout:
			showTimePickerDialog(dayStopTv);
			break;
		case R.id.nightStartRelativelayout:
			showTimePickerDialog(nightStartTv);
			break;
		case R.id.nightStopRelativelayout:
			showTimePickerDialog(nightStopTv);
			break;
		case R.id.repeatRelativeLayout:
			dialog.show();
			break;
		default:
			break;
		}
	}

	/**
	 * 比较白天模式和晚上模式开始时间和结束时间先后顺序
	 * 
	 * @param hour
	 *            当前选择的小时
	 * @param minute
	 *            当前选择的分钟
	 * @param comepartToTime
	 *            用于比较的TextView,如果设置开始时间,则以结束做比较,反之亦然
	 * @param isDayTime
	 *            是否为白天模式 :true代表白天模式,false代表夜晚模式
	 * */
	private boolean compareTime(int hour, int minute, TextView comepartToTime,
			boolean isDayTime) {
		if (isDayTime) {
			if ((hour == Constants.DAY_START_HOUR && minute == Constants.DAY_START_MINUTE)
					|| (hour == Constants.DAY_STOP_HOUR && minute == Constants.DAY_STOP_MINUTE)) {

			} else {

				if ((!timeCanSet(Constants.DAY_START_HOUR,
						Constants.DAY_START_MINUTE, hour, minute, isDayTime) || !timeCanSet(
						hour, minute, Constants.DAY_STOP_HOUR,
						Constants.DAY_STOP_MINUTE, isDayTime))) {
					Show.toast(activity, R.string.sub_day_time_scope);
					return false;
				}
			}
		} else {
			if ((hour == Constants.NIGHT_START_HOUR && minute == Constants.NIGHT_START_MINUTE)
					|| (hour == Constants.NIGHT_STOP_HOUR && minute == Constants.NIGHT_STOP_MINUTE)) {

			} else {

				if ((!timeCanSet(Constants.NIGHT_START_HOUR,
						Constants.NIGHT_START_MINUTE, hour, minute, isDayTime) || !timeCanSet(
						hour, minute, Constants.NIGHT_STOP_HOUR,
						Constants.NIGHT_STOP_MINUTE, isDayTime))) {
					Show.toast(activity, R.string.sub_night_time_scope);
					return false;
				}
			}
		}
		String comepareTime = comepartToTime.getText().toString();
		int comepareHour = Integer.parseInt(comepareTime.substring(0, 2));
		int comepareMinute = Integer.parseInt(comepareTime
				.substring(comepareTime.length() - 2));
		switch (comepartToTime.getId()) {

		case R.id.dayStarttv:
			if (!timeCanSet(comepareHour, comepareMinute, hour, minute,
					isDayTime)) {
				Show.toast(activity, R.string.sub_stop_time_check);
				return false;
			}
			break;
		case R.id.dayStoptv:
			if (!timeCanSet(hour, minute, comepareHour, comepareMinute,
					isDayTime)) {
				Show.toast(activity, R.string.sub_start_time_check);
				return false;
			}
			break;
		case R.id.nightStarttv:
			if (!timeCanSet(comepareHour, comepareMinute, hour, minute,
					isDayTime)) {
				Show.toast(activity, R.string.sub_stop_time_check);
				return false;
			}
			break;
		case R.id.nightStoptv:
			if (!timeCanSet(hour, minute, comepareHour, comepareMinute,
					isDayTime)) {
				Show.toast(activity, R.string.sub_start_time_check);
				return false;
			}
			break;
		default:
			return false;
		}
		return true;
	}

	/**
	 * 比较两个时间的先后顺序
	 * 
	 * @param startHour
	 *            开始小时数
	 * @param startMinute
	 *            开始分钟数
	 * @param stopHour
	 *            截止小时数
	 * @param stopMinute
	 *            截止分钟数
	 * @param isDayMode
	 *            模式：true-白天 false-夜晚
	 * @return true-截止时间在开始时间之后 false-截止时间在开始时间之前
	 * */
	private boolean timeCanSet(int startHour, int startMinute, int stopHour,
			int stopMinute, boolean isDayMode) {
		// boolean addDate = false;
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, startHour);
		calendar.set(Calendar.MINUTE, startMinute);
		// if (!isDayMode) {
		// if (Constants.NIGHT_START_HOUR > 12) {
		// if (startHour <= Constants.NIGHT_STOP_HOUR) {
		// calendar.add(Calendar.DATE, 1);
		// addDate = true;
		// }
		// }
		// }
		long startMillions = calendar.getTimeInMillis();
		// if (addDate) {
		// calendar.add(Calendar.DATE, -1);
		// }
		// if (!isDayMode) {
		// if (Constants.NIGHT_START_HOUR > 12) {
		// if (stopHour <= Constants.NIGHT_STOP_HOUR) {
		// calendar.add(Calendar.DATE, 1);
		//
		// }
		// }
		// }
		calendar.set(Calendar.HOUR_OF_DAY, stopHour);
		calendar.set(Calendar.MINUTE, stopMinute);
		long stopMillions = calendar.getTimeInMillis();
		return stopMillions - startMillions > 0 ? true : false;
	}

	@Override
	public void reFresh(TreeSet<Integer> chooseDay) {
		switch (chooseDay.size()) {
		case 0:
			Show.toast(activity, R.string.sub_alarm_time_null);
			repeatDay.setText(getString(R.string.sub_time_everyday));
			break;
		case 7:
			repeatDay.setText(getString(R.string.sub_time_everyday));
			break;
		case 5:
			if (!chooseDay.contains(1) && !chooseDay.contains(7)) {
				repeatDay.setText(getString(R.string.sub_time_workday));
			} else {
				repeatDay.setText(setChooseDay(chooseDay));
			}
			break;
		default:
			repeatDay.setText(setChooseDay(chooseDay));
			break;
		}
	}

	/**
	 * 转换chooseDay为服务器要求格式
	 * 
	 * @param chooseDay
	 * @return
	 */
	public String setChooseDay(TreeSet<Integer> chooseDay) {
		Iterator<Integer> iterator = chooseDay.iterator();
		StringBuffer sb = new StringBuffer(" ");
		while (iterator.hasNext()) {
			switch (iterator.next()) {
			case 1:
				sb.append(getString(R.string.sub_week_sunday));
				sb.append(",");
				break;
			case 2:
				sb.append(getString(R.string.sub_week_monday));
				sb.append(",");
				break;
			case 3:
				sb.append(getString(R.string.sub_week_tuesday));
				sb.append(",");
				break;
			case 4:
				sb.append(getString(R.string.sub_week_wednesday));
				sb.append(",");
				break;
			case 5:
				sb.append(getString(R.string.sub_week_thursday));
				sb.append(",");
				break;
			case 6:
				sb.append(getString(R.string.sub_week_friday));
				sb.append(",");
				break;
			case 7:
				sb.append(getString(R.string.sub_week_saturday));
				sb.append(",");
				break;
			default:
				break;
			}
		}
		String target = sb.toString();
		return target.substring(0, target.length() - 1);
	}

	protected void saveStatus() {
		super.saveStatus();
		if (!isSetted) {
			finish();
			return;
		}
		upLoadDeviceSet(handler);
	}

	/**
	 * 上传采集端机设置 从本地取得设置信息后给device赋值并上传至服务器
	 * */
	public void upLoadDeviceSet(Handler handler) {
		Log.d("subonline", NetManager.subOnLineMap.get(uuid).toString());
		if (App.isLogin) {
			if (!NetManager.subOnLineMap.get(uuid).toString().equals("ONLINE")) {
				Show.toast(con, R.string.sub_off_line);
				return;
			}
		} else {
			Show.toast(con, R.string.please_login);
			return;
		}
		if (null == progressDialog) {
			progressDialog = SubUtils.showProgress(con);
		} else {
			progressDialog.show();
		}
		Device device = new Device();
		device.setDiviceId(id);
		device.setUuid(uuid);
		String dayStart = dayStartTv.getText().toString();
		String dayStop = dayStopTv.getText().toString();
		String mesures = SharedPrefsUtil.getStringValue(con,
				Constants.ALARM_MEASURES, getString(R.string.sub_body_recg));
		String alarm = SharedPrefsUtil.getStringValue(con,
				Constants.AlARM_METHODS, getString((R.string.sub_take_one)));
		String voice = SharedPrefsUtil.getStringValue(con,
				Constants.AlARM_PLAY_VOICE,
				getString((R.string.sub_states_null)));
		String nightStart = nightStartTv.getText().toString();
		String nightStop = nightStopTv.getText().toString();
		boolean flashLight = SharedPrefsUtil.getBooleanValue(con,
				Constants.FLASH_LIGHT, true);
		TreeSet<Integer> chooseSet = subUtils.getWeekDaySet(
				con,
				SharedPrefsUtil.getSetValue(con, Constants.WEEK_DAY,
						subUtils.initWeekSet(con)));

		device.setStartTWhite(dayStart);
		device.setEndTWhite(dayStop);
		device.setDeterrenceVWhite(voice);
		device.setLarmWhite(alarm);
		device.setStartTNight(nightStart);
		device.setEndTNight(nightStop);
		device.setLarmNight(alarm);
		device.setDeterrenceVNight(voice);
		device.setHumanR(mesures.equals(getString(R.string.sub_body_recg)));
		device.setMotionD(!mesures.equals(getString(R.string.sub_body_recg)));
		device.setFlashlight(flashLight);
		device.setWeekWhite(getWeekStr(chooseSet));
		device.setWeekNight(getWeekStr(chooseSet));
		App.netManager.setCollectionTerminal(device, handler);
	}

	/**
	 * 将TreeSet 变为字符串1,2,3,...等上传
	 * */
	private String getWeekStr(TreeSet<Integer> chooseSet) {
		StringBuffer sb = new StringBuffer("");
		Iterator<Integer> it = chooseSet.iterator();
		while (it.hasNext()) {
			int day = it.next();
			sb.append(day);
			sb.append(",");
		}
		String week = sb.toString();
		return week.substring(0, week.length() - 1);
	}
}
